
var EpyUser = new Class({
    Implements: [Events, Options],
    options: {
        'tagid': ''
    },
    initialize: function(opts) {
        this.setOptions(opts);

        this.panel = document.id(this.options.tagid);
        if(!this.panel) return;
        this.panel.empty();

        //
        this.getUsers = new Request({
            url: '/Admin/webstat/httpservice',
            onRequest: function() {
                new ShowBox().say('Load...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var data = [];
                try {
                    data = eval('(' + resp + ')');
                }
                catch(err) { alert('Error...\n' + err); return; }
                new Loader().hide();

                this.userItems_showUsers(data);
            }.bind(this),
            onError: function(text, error) {
                console.log('getUsers:text=',text,'\nerror',error);
            }
        }).send('table=epy&ex=getUsers&nc=' + Date.now());
    },
    userItems_showUsers: function(data) {

        this.content = new Element('div#content');
        this.content.empty();
        this.listData = new Element('div');

        this.panel.adopt(
            new Element('div.tl[html=<div class="tr"><div>&nbsp;</div></div>]'),
            this.content.adopt(this.listData),
            new Element('div.bl[html=<div class="br"><div>&nbsp;</div></div>]')
        )

        var tbody = new Element('tbody');
        var table = new Element('table#listData', {'rules':'groups'}).adopt(
            new Element('thead', { html: '<tr><th class="imgCol">&nbsp;</th><th class="brdCol w200">User Name</th class="tdFull"><th>&nbsp;</th></tr>' }),
            new Element('tfoot', { html: '<tr><th class="tdFull" colspan=3>&nbsp;</th></tr>' }),
            tbody
        );
        tbody.empty();

        //
        var user, color, tdo, tagid;
        for(var i = 0; i < data.users.length; i++) {
            user = data.users[i];

            tagid = 'usr_' + i;
            tdo = new Element('td.imgCol').adopt(
                new Element('a.plus[html=&nbsp;][href=javascript:;][title=Open Groups]',{
                    'events': {
                        'click': this.userItems_getGroups.bind(this, user.id, tagid),
                        'focus': function() {this.blur();}
                    }
                })
            );

            tbody.adopt(
                new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]').adopt(
                    tdo,
                    new Element('td.brdCol[text=' + user.name + ']'),
                    new Element('td.tdFull[html=&nbsp;]')
                ),
                new Element('tr#x' + tagid + '[style=display:none;]').adopt(
                    new Element('td[html=&nbsp;]'),
                    new Element('td#d' + tagid + '[colspan=3][style=padding-top:0;]')
                )
            );
        } // for

        this.listData.adopt(table);
    },
    userItems_getGroups: function(userid, tagid, evt) {
        evt.stop();

        var xcuc = document.id('x' + tagid);
        var dcuc = document.id('d' + tagid);
        if(evt.target.hasClass('plus')) {
            evt.target.removeClass('plus').addClass('minus');

            this.userItems_getGroups = new Request({
                url: '/Admin/webstat/httpservice',
                onRequest: function() {
                    new ShowBox().say('Load...');
                    new Loader().show();
                },
                onComplete: function(resp) {
                    var data = [];
                    try {
                        data = eval('(' + resp + ')');
                    }
                    catch(err) {
                        alert('Error epyUser:\n' + err);
                        return;
                    }

                    new Loader().hide();

                    this.userItems_showGroups(data, userid, dcuc);
                }.bind(this)
            }).send('table=epy&ex=getGroups&userid=' + userid + '&nc=' + Date.now());

            xcuc.set('styles', {'display':'','background-color':'#ffffff'});
        }
        else {
            evt.target.removeClass('minus').addClass('plus');

            xcuc.setStyle('display', 'none');
        }

    },
    userItems_showGroups: function(data, userid, dcuc) {

        dcuc.empty();

        var table = new Element('table#listData', {'rules':'groups'}), tbody = new Element('tbody');

        dcuc.adopt(
            table.adopt(
                new Element('thead', { html: '<tr><th class="imgCol">&nbsp;</th><th class="imgCol">&nbsp;</th><th class="brdCol w150">Group Name</th><th class="brdCol w50">Active</th><th class="tdFull">&nbsp;</th></tr>' }),
                new Element('tfoot', { html: '<tr><th class="tdFull" colspan=5>&nbsp;</th></tr>' }),
                tbody
            )
        );

        var group, color, tdo, tde, tagid;
        for(var i = 0; i < data.groups.length; i++) {
            group = data.groups[i];

            tagid = 'grp_' + i + '_' + userid;
            tdo = new Element('td.imgCol').adopt(
                new Element('a.plus[html=&nbsp;][href=javascript:;][title=Open Items]',{
                    'events': {
                        'click': this.userItems_getItems.bind(this, group.id, tagid),
                        'focus': function() {this.blur();}
                    }
                })
            );

            tde = new Element('td.imgCol').adopt(
                new Element('a.edit[html=&nbsp;][href=javascript:;][title=Edit Group]',{
                    'events': {
                        'click': this.userItems_editGroup.bind(this, userid, group.id),
                        'focus': function() {this.blur();}
                    }
                })
            );

            tbody.adopt(
                new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]').adopt(
                    tdo,
                    tde,
                    new Element('td.brdCol[text=' + group.name + ']'),
                    new Element('td.imgCol[html=<a href="javascript:;" class="' + (group.act ? 'check1': 'check0') + '">&nbsp;</a>]'),
                    new Element('td.tdFull[html=&nbsp;]')
                ),
                new Element('tr#x' + tagid + '[style=display:none;]').adopt(
                    new Element('td[html=&nbsp;]'),
                    new Element('td#d' + tagid + '[colspan=4][style=padding-top:0;]')
                )
            );
        } // for

    },
    userItems_getItems: function(groupid, tagid, evt) {
        evt.stop();

        var xcuc = document.id('x' + tagid);
        var dcuc = document.id('d' + tagid);
        if(evt.target.hasClass('plus')) {
            evt.target.removeClass('plus').addClass('minus');

            this.userItems_getItems = new Request({
                url: '/Admin/webstat/httpservice',
                onRequest: function() {
                    new ShowBox().say('Load...');
                    new Loader().show();
                },
                onComplete: function(resp) {
                    var data = [];
                    try {
                        data = eval('(' + resp + ')');
                    }
                    catch(err) {
                        alert('Error epyUser:\n' + err);
                        return;
                    }

                    new Loader().hide();

                    this.userItems_showItems(data, groupid, dcuc);
                }.bind(this),
                onError: function(text, error) {
                    console.log('getItems:text=',text,'\nerror',error);
                }
            }).send('table=epy&ex=getItems&groupid=' + groupid + '&nc=' + Date.now());

            xcuc.set('styles', {'display':'','background-color':'#ffffff'});
        }
        else {
            evt.target.removeClass('minus').addClass('plus');

            xcuc.setStyle('display', 'none');
        }

    },
    userItems_showItems: function(data, groupid, dcuc) {

        dcuc.empty();

        var tbody = new Element('tbody');
        var create = new Element('a.create[href=javascript:;][title=Add New Item]', {
            'events': {
                'click': this.userItems_createNewItem.bind(this, groupid),
                'focus': function() {this.blur();}
            }
        });
        dcuc.adopt(
            new Element('table#listData[rules=groups]').adopt(
                new Element('thead').adopt(
                    new Element('tr').adopt(
                        new Element('th.imgCol').adopt(create),
                        new Element('th.brdCol.w50[text=SKU]'),
                        new Element('th.brdCol.w120[text=Item Name]'),
                        new Element('th.brdCol.w50[text=Send]'),
                        new Element('th.brdCol.w50[html=Compuvest<br/>Qty]'),
                        new Element('th.brdCol.w50[html=Amazon<br/>Qty]'),
                        new Element('th.brdCol.w50[html=Amazon<br/>Price]'),
                        new Element('th.brdCol.w50[html=AmzComp<br/>Qty]'),
                        new Element('th.brdCol.w50[html=AmzComp<br/>Price]'),
                        new Element('th.brdCol.w50[html=Ebay<br/>Qty]'),
                        new Element('th.brdCol.w50[html=Ebay<br/>Price]'),
                        new Element('th.brdCol.w50[html=EbayA<br/>Qty]'),
                        new Element('th.brdCol.w50[html=EbayA<br/>Price]'),
                        new Element('th.brdCol.w50[html=Buycom<br/>Qty]'),
                        new Element('th.brdCol.w50[html=Buycom<br/>Price]')
                    )
                ),
                new Element('tfoot', { html: '<tr><th class="tdFull" colspan=15>&nbsp;</th></tr>'}),
                tbody
            )
        );

        var item, color = false;
        for(var i = 0; i < data.items.length; i++) {
            item = data.items[i];

            tbody.adopt(
                new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]').adopt(
                    // edit item
                    new Element('td.imgCol').adopt(
                        new Element('a.edit[html=&nbsp;][href=javascript:;][title=Update or Delete item]',{
                            'events': {
                                'click': this.userItems_editItem.bind(this, item.id, groupid),
                                'focus': function() {this.blur();}
                            }
                        })
                    ),
                    new Element('td.brdCol.w50[text=' + item.sku + ']'),
                    new Element('td.brdCol.w120[html=' + item.name + ']'),
                    new Element('td.imgCol[html=<a href="javascript:;" class="' + (item.send ? 'check1': 'check0') + '">&nbsp;</a>]'),
                    new Element('td.brdCol.center.w50[text=' + item.qty + ']'),
                    new Element('td.brdCol.center.w50[text=' + (item.amazonQty || '') + ']'),
                    new Element('td.brdCol.center.w50[text=' + formatprice(item.amazonPrice) + ']'),
                    new Element('td.brdCol.center.w50[text=' + (item.amzcompQty || '') + ']'),
                    new Element('td.brdCol.center.w50[text=' + formatprice(item.amzcompPrice) + ']'),
                    new Element('td.brdCol.center.w50[text=' + (item.ebayQty || '') + ']'),
                    new Element('td.brdCol.center.w50[text=' + formatprice(item.ebayPrice) + ']'),
                    new Element('td.brdCol.center.w50[text=' + (item.ebayAliQty || '') + ']'),
                    new Element('td.brdCol.center.w50[text=' + formatprice(item.ebayAliPrice) + ']'),
                    new Element('td.brdCol.center.w50[text=' + (item.buycomQty || '') + ']'),
                    new Element('td.brdCol.center.w50[text=' + formatprice(item.buycomPrice) + ']')
                )
            )
        }

    },
    userItems_editGroup: function(userid, groupid, evt) {
        evt.stop();

        new UserItems_EditGroup({
            'userid'  : userid,
            'groupid' : groupid,
            'targetid': evt.target,
            'onReload': function(userid) {

                this.userItems_getGroups.send('table=epy&ex=getGroups&userid=' + userid + '&nc=' + Date.now());
            }.bind(this)
        });
    },
    userItems_createNewItem: function(groupid, evt) {
        evt.stop();

        new UserItems_CreateNewItem({
            'groupid' : groupid,
            'targetid': evt.target,
            'onReload': function(groupid) {

                this.userItems_getItems.send('table=epy&ex=getItems&groupid=' + groupid + '&nc=' + Date.now());
            }.bind(this)
        });
    },
    userItems_editItem: function(itemid, groupid, evt) {
        evt.stop();

        new UserItems_EditItem({
            'itemid'  : itemid,
            'groupid' : groupid,
            'targetid': evt.target,
            'onReload': function(groupid) {

                this.userItems_getItems.send('table=epy&ex=getItems&groupid=' + groupid + '&nc=' + Date.now());
            }.bind(this)
        });
    }

});

var UserItems_EditGroup = new Class({
    Implements: [Events, Options],
    options: {
        userid: 0,
        groupid: 0,
        targetid: null
    },
    initialize: function(options) {
        this.setOptions(options);

        this.editgroup = new Request({
            url: '/Admin/webstat/httpservice',
            onRequest: function() {
                new ShowBox().say('Edit...');

                this.options.targetid.removeClass('edit').addClass('load');
            }.bind(this),
            onComplete: function(resp) {
                this.options.targetid.removeClass('load').addClass('edit');

                this.makeForm(eval('(' + resp + ')'));
            }.bind(this)
        }).send('table=epy&ex=editGroup&groupid=' + this.options.groupid + '&userid=' + this.options.userid + '&nc=' + Date.now());

    },
    makeForm: function(data) {

        var group = data.group;

        this.update = new Element('a.update.closeThis[href=javascript:;][title=Update Group][html=<em>Update</em>]');
        this.create = new Element('a.create.closeThis[href=javascript:;][title=Create New Group][html=<em>Create New Group</em>]');
        this.erase  = new Element('a.erase.closeThis[href=javascript:;][title=Erase Group][html=<em>Erase</em>]');

        //make body
        this.table = new Element('table#ggroup').adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(
                    new Element('th.col[colspan=3][html=Group Name : <input style="text-align:left;width:200px;" name="name" type="text" maxlength=50 value="' + group.name + '"/>]'),
                    new Element('th.col[colspan=2]').adopt(
                        new Element('label[html=Active&nbsp;&nbsp;]'),
                        new Element('input[type=checkbox][name=active]').set('checked', group.active)
                    )
                ),
                new Element('tr', { html: '<td class="sep" colspan=5><hr/></td>' }),
                new Element('tr').adopt(
                    new Element('td.col').adopt(
                        this.update
                    ),
                    new Element('td.col[colspan=2]').adopt(
                        this.create
                    ),
                    new Element('td.col[colspan=2]').adopt(
                        this.erase
                    )
                )
            )
        );

        new ModalBox({
            width: 450,
            modal: {
                background: '#555'
            },
            onOpen: function() {
                this.update.addEvents({'click': this.updateGroup.bind(this, group.uid, group.gid),  'focus': function() {this.blur();} });
                this.create.addEvents({'click': this.createGroup.bind(this, group.uid),             'focus': function() {this.blur();} });
                this.erase.addEvents( {'click': this.eraseGroup.bind(this, group.uid, group.gid),   'focus': function() {this.blur();} });
            }.bind(this)
        }).doBox('<h2>Group: ' + group.name + '</h2>', new Element('center').adopt(this.table));

    },
    updateGroup: function(userid, groupid) {

        var inpts = this.table.getElements('input'), parms = '&groupid=' + groupid + '&userid=' + userid + '&cb=';
        inpts.each(function(inp, idx) {
            parms += (idx++ > 0 ? ',' : '') + inp.get('name') + '=\'' + (inp.get('type') == 'text' ? (inp.get('value') || ''): (inp.get('checked') ? 1: 0)) +'\'';
        });

        new Request({ url: '/Admin/webstat/httpservice' }).send('table=epy&ex=updateGroup&nc=' + Date.now() + parms);

        this.fireEvent('reload', userid);
    },
    createGroup: function(userid) {

        var inpts = this.table.getElements('input'), parms = '&userid=' + userid + '&cb=';
        inpts.each(function(inp, idx) {
            parms += (idx++ > 0 ? ',' : '') + inp.get('name') + '=\'' + (inp.get('type') == 'text' ? (inp.get('value') || '') : (inp.get('checked') ? 1 : 0)) +'\'';
        });

        new Request({ url: '/Admin/webstat/httpservice' }).send('table=epy&ex=createGroup&nc=' + Date.now() + parms);

        this.fireEvent('reload', userid);
    },
    eraseGroup: function(userid, groupid) {

        new Request({ url: '/Admin/webstat/httpservice' }).send('table=epy&ex=deleteGroup&groupid=' + groupid + '&nc=' + Date.now());

        this.fireEvent('reload', userid);
    }
});

var UserItems_EditItem = new Class({
    Implements: [Events, Options],
    options: {
        groupid : 0,
        itemid  : 0,
        newitem : false,
        targetid: null
    },
    initialize: function(options) {
        this.setOptions(options);

        this.edititem = new Request({
            url: '/Admin/webstat/httpservice',
            onRequest: function() {
                new ShowBox().say('get Item...');

                this.options.targetid.removeClass('edit').addClass('load');
            }.bind(this),
            onComplete: function(resp) {
                this.options.targetid.removeClass('load').addClass('edit');

                this.makeItemForm(eval('(' + resp + ')'));
            }.bind(this),
            onError: function(text, error) {
                console.log('UserItems_EditItem:text=',text,'\nerror',error);
            }
        }).send('table=epy&ex=getItem&itemid=' + (this.options.itemid || 0) + '&nc=' + Date.now());

    },
    makeItemForm: function(data) {
        var item = data.item;

        this.update = new Element('a.update.closeThis[href=javascript:;][title=Update Item][html=<em>Update</em>]');
        this.deleted = new Element('a.erase.closeThis[href=javascript:;][title=Delete Item][html=<em>Delete</em>]');

        //make body
        this.table = new Element('table#ggroup').adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(new Element('th.col[colspan=3][style=color:white;][html=' + item.name + ']')),
                new Element('tr', { html: '<td class="sep" colspan=3><hr/></td>'}),
                new Element('tr', { html: '<th class="col">Cost price</th><th class="col">Sell Price</th><th class="col">Qty</th>'}),
                new Element('tr').adopt(
                    new Element('td.col[html=' + formatprice(item.costPrice) + ']'),
                    new Element('td.col[html=' + formatprice(item.sellPrice) + ']'),
                    new Element('td.col[html=' + item.qty + ']')
                ),
                new Element('tr', { html: '<td class="sep" colspan=3><hr/></td>'}),
                new Element('tr', { html: '<th class="col">&nbsp;</th><th class="col">Price</th><th class="col">Qty</th>'}),
                new Element('tr', { html: '<th class="col">Amazon</th>' +
                    '<td class="col"><input type="text" maxlength=10 name="amazonPrice" value="' + (item.amazonPrice ? numberFormat(item.amazonPrice) : '') + '"/></td>' +
                    '<td class="col"><input type="text" maxlength=5 name="amazonQty" value="' + (item.amazonQty || '') + '"/></td>'
                }),
                new Element('tr').adopt(
                    new Element('th.col[text=Amzcomp]'),
                    new Element('td.col[html=<input type="text" maxlength=10 name="amzcompPrice" value="' + (item.amzcompPrice ? numberFormat(item.amzcompPrice) : '') + '"/>]'),
                    new Element('td.col[html=<input type="text" maxlength=5 name="amzcompQty" value="' + (item.amzcompQty || '') + '"/>]')
                ),
                new Element('tr').adopt(
                    new Element('th.col[text=Ebay]'),
                    new Element('td.col[html=<input type="text" maxlength=10 name="ebayPrice" value="' + (item.ebayPrice ? numberFormat(item.ebayPrice) : '') + '"/>]'),
                    new Element('td.col[html=<input type="text" maxlength=5 name="ebayQty" value="' + (item.ebayQty || '') + '"/>]')
                ),
                new Element('tr').adopt(
                    new Element('th.col[text=EbayA]'),
                    new Element('td.col[html=<input type="text" maxlength=10 name="ebayAliPrice" value="' + (item.ebayAliPrice ? numberFormat(item.ebayAliPrice) : '') + '"/>]'),
                    new Element('td.col[html=<input type="text" maxlength=5 name="ebayAliQty" value="' + (item.ebayAliQty || '') + '"/>]')
                ),
                new Element('tr').adopt(
                    new Element('th.col[text=Buy.com]'),
                    new Element('td.col[html=<input type="text" maxlength=10 name="buycomPrice" value="' + (item.buycomPrice ? numberFormat(item.buycomPrice) : '') + '"/>]'),
                    new Element('td.col[html=<input type="text" maxlength=5 name="buycomQty" value="' + (item.buycomQty || '') + '"/>]')
                ),
                new Element('tr', { html: '<td class="sep" colspan=3><hr/></td>'}),
                new Element('tr').adopt(
                    new Element('td.col').adopt(
                        new Element('input[type=checkbox][name=send]').set('checked', item.send),
                        new Element('em[text=Send]')
                    ),
                    new Element('td.col').adopt(this.update),
                    new Element('td.col[colspan=2]').adopt(this.deleted)
                ),
                new Element('tr', { html: '<td colspan=3>&nbsp;</td>'})
            )
        );

        new ModalBox({
            width: 450,
            modal: {
                background: '#555'
            },
            onOpen: function() {
                this.update.addEvents( {'click': this.updateItem.bind(this, item.id), 'focus': function() {this.blur();} });
                this.deleted.addEvents({'click': this.deleteItem.bind(this, item.id), 'focus': function() {this.blur();} });
            }.bind(this)
        }).doBox('<h2>Sku: ' + item.sku + '</h2>', new Element('center').adopt(this.table));

    },
    updateItem: function(itemid) {

        var inpts = this.table.getElements('input'), parms = '&cb=';
        inpts.each(function(inp, idx) {
            parms += (idx++ > 0 ? ',' : '') +
                     inp.get('name') + '=\'' +
                     (inp.get('type') == 'text' ? (inp.get('value') ? inp.get('value').replace(',','').replace('$','') : 0) : (inp.get('checked') ? 1 : 0)) +'\'';
        });

        new Request({
            url: '/Admin/webstat/httpservice'
        }).send('table=epy&ex=updateItem&itemid=' + itemid + '&nc=' + Date.now() + parms);

        this.fireEvent('reload', this.options.groupid);
    },
    deleteItem: function(itemid) {

        new Request({ url: '/Admin/webstat/httpservice' }).send('table=epy&ex=deleteItem&itemid=' + itemid + '&nc=' + Date.now());

        this.fireEvent('reload', this.options.groupid);
    }
});

var UserItems_CreateNewItem = new Class({
    Implements: [Events, Options],
    options: {
        groupid : 0,
        targetid: null
    },
    initialize: function(options) {
        this.setOptions(options);


        this.search = new Element('button.closeThis[text=Search][title=Search Item]');

        this.table = new Element('table#ggroup').adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(
                    new Element('th[html=SKU :]'),
                    new Element('td[html=<input style="text-align:left;width:120px;" name="search" type="text" maxlength=15 value=""/>]'),
                    new Element('td').adopt(this.search)
                ),
                new Element('tr', { html: '<td class="sep" colspan=3><hr/></td>'}),
                new Element('tr', { html: '<td colspan=3>&nbsp;</td>'})
            )
        );

        new ModalBox({
            width: 250,
            modal: {
                background: '#555'
            },
            onOpen: function() {
                this.search.addEvents( {'click': this.searchItem.bind(this), 'focus': function() {this.blur();} });
            }.bind(this)
        }).doBox('<h2>Search Item</h2>', new Element('center').adopt(this.table));

    },
    searchItem: function(evt) {

        var sku = this.table.getElement('input[name="search"]');
        if(!sku.get('value')) return;

        new Request({
            url: '/Admin/webstat/httpservice',
            onRequest: function() {
            },
            onComplete: function(resp) {

                this.insertItem(eval('(' + resp + ')'));
            }.bind(this),
            onError: function(text, error) {
                console.log('UserItems_EditItem:searchItem text=',text,'\nerror',error);
            }
        }).send('table=epy&ex=searchItem&sku=' + (sku.get('value') || 0) + '&nc=' + Date.now());

    },
    insertItem: function(data) {
        new Request({
            url: '/Admin/webstat/httpservice'
        }).send('table=epy&ex=insertItem&itemid=' + data.item.id + '&groupid=' + this.options.groupid + '&sku=' + data.item.sku + '&nc=' + Date.now());

        this.fireEvent('reload', this.options.groupid);

    }
});
